package top.lethelh.socket;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

/**
 * @author lh
 * @date 2021/11/24 9:19 下午
 * @desc UDP客户端
 */
public class UDPClient {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket()) {
            byte[] buff = "Hello World!".getBytes(StandardCharsets.UTF_8);
            InetAddress address = InetAddress.getByName("127.0.0.1");
            DatagramPacket packet = new DatagramPacket(buff, buff.length, address, 65001);

            socket.send(packet);

            byte[] data = new byte[100];
            DatagramPacket receivedPacket = new DatagramPacket(data, data.length);

            socket.receive(receivedPacket);

            String text = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            System.out.println(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
